import { uuid } from "@inbiz/utils";
import { setApi, updateApi } from "./service";


const queryFieldToShowFields = (apiData: any) => {
  const index = apiData?.outConfig?.findIndex(
    (item: { Childrens: string | any[] }) => item.Childrens?.length,
  );
  if (index == -1 || index === undefined) {
    return [];
  }
  return (
    apiData?.outConfig[index]?.Childrens?.map((item: any) => {
      return {
        ...item,
        FieldName: item.Name,
      };
    }) || []
  );
}

export const isString = (value: any) => {
  if (typeof value === 'string') return value;
  if (value?.search && typeof value.search === 'string') return value.search;
  if (value?.search && typeof value.edit === 'string') return value.edit;
  return false
}

export const saveApiData = async ({ queryData, value, interfaceType, isPrimaryKey, form }: {
  queryData: any
  value: string | object;
  interfaceType?: number;
  isPrimaryKey?: boolean;
  form: any
}) => {
  const { appInfo } = form as unknown as { appInfo: { appId: string } };
  let searchFilter = [];
  const outData = queryData?.searchData?.outData || queryData?.editData?.outData;
  if (outData) {
    searchFilter = outData
      .find((item: { children: any }) => item.children)
      ?.children?.filter((v: any) => {
        return v.IsSingle;
      });
  }
  if (!searchFilter?.length && isPrimaryKey) {
    return Promise.reject('ApiQuery.selectQueryKey');
  }
  let editFilter = queryData?.editData?.outData?.[1]?.children?.filter((v: any) => {
    return v.IsSingle;
  });
  if (queryData?.editData?.inputData.length && !editFilter?.length) {
    return Promise.reject('ApiQuery.selectEditKey');
  }
  const params: any = {
    appId: appInfo.appId,
    name: uuid(8, 62),
    souceType: 1,
    groupkey: '0',
    interfaceQueryConfig: {
      selectConfig: {
        key: queryData?.searchData?.selectDatas[0]?.MethodKey,
        inputConfig: queryData?.searchData?.inputData,
        outConfig: queryData?.searchData?.outData?.map((item: any) => {
          return { ...item, Childrens: item.children };
        }),
      },
      interfaceType
    },
  };
  if (interfaceType === 2) {
    params.interfaceQueryConfig = {
      editConfig: {
        key: queryData?.searchData?.selectDatas[0]?.MethodKey,
        inputConfig: queryData?.searchData?.inputData,
        outConfig: queryData?.searchData?.outData?.map((item: any) => {
          return { ...item, Childrens: item.children };
        }),
      },
      interfaceType
    }
  }
  const apiPrimaryColumn = form?.query(/apiPrimaryColumn$/)?.take();
  if (apiPrimaryColumn && 'value' in apiPrimaryColumn) {
    apiPrimaryColumn.value = {
      searchKeyName: searchFilter?.[0]?.Name,
      editKeyName: editFilter?.[0]?.Name,
    };
  }
  let _value = '';
  const key = isString(value)
  if (!key) {
    const res = await setApi(params);
    _value = res.Data;
  } else {
    _value = key;
    await updateApi({ ...params, key: key });
  }
  const queryField = queryFieldToShowFields(params.interfaceQueryConfig.selectConfig);
  const primaryKey = queryField.find((item: { IsSingle: any }) => item.IsSingle)?.Name ?? '';
  return {
    value: _value,
    date: Date.now(),
    sourcetype: 'api',
    primaryKey,
    queryField,
  };
}



 
export function toCase(json: unknown){ 
  if(json && typeof json == 'object'){ 
    if(Array.isArray(json)){ 
      json.forEach(function(item){ toCase(item); }) 
    } else { 
      for (let key in json){ 
        //@ts-ignore
        var item = json[key]; 
        if(typeof item == 'object'){ 
          toCase(item);
        } 
        //@ts-ignore
        delete(json[key]);
        //@ts-ignore
        json[key.toLocaleLowerCase()] = item 
      } 
    } 
  } else {
    return json
  }
} 